<?php
declare (strict_types=1);

namespace app\model\home;

use app\common\model\BaseModel;
use app\common\model\Member;
use app\common\model\Store;
use app\model\admin\Grade;
use \libs\Log;

class Order extends BaseModel
{
    protected $pk = 'id';

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * @param $value
     * @return false|string
     * 付款时间
     */
    protected function getPayTimeAttr($value)
    {
        return date('Y-m-d H:i', $value);
    }

    /**
     * @param $value
     * @return string
     * 订单类型
     */
    protected function getOrderTypeStrAttr($value)
    {
        $orderType = [
            1 => '助教',
            2 => '包间',
            3 => '道具',
            4 => '抛班',
            5 => '年卡',
            6 => '购物车支付',
            7 => '充值',
        ];
        return $orderType[$value];
    }

    /**
     * @param $value
     * 所属门店
     */
    protected function getStoreNameAttr($value)
    {
        return Store::where('id', $value)->value('store_name') ?: '';
    }

    /**
     * 获得列表
     * @param bool $where
     * @param string $fields
     * @param string|null $order
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($where = true, $fields = '*', $order = null, $page = 1, $pageSize = 20)
    {
        $data = [
            'count' => 0,
            'list' => []
        ];
        $count = $this->where($where)->count();
        if (empty($count)) {
            return $this->returnRight($data);
        }
        $order = is_null($order) ? $this->pk . ' desc' : $order;
        $list = $this->where($where)
            ->field($fields)
            ->order($order)
            ->page($page, $pageSize)
            ->select();
        foreach ($list->toArray() as $item) {
            switch ($item['order_type']) {
                case 2:
                    $name = Room::where('id', $item['re_id'])->value('room_title') ?: '';
                    break;
                default:
                    $name = Assistant::where('id', $item['re_id'])->value('nickname') ?: '';
                    break;
            }
            $item['re_name'] = $name;
            $listArr[] = $item;
        }
        $data['count'] = $count;
        $data['list'] = $listArr;
        return $this->returnRight($data);
    }

    /**
     * @param $data
     * @return array
     * 创建订单
     */
    public function createOrder($data)
    {
        $data['order_no'] = makeOrderNo();
        if ($data['order_type'] == 4) {
            $retArr = getConfig('cast_off');
            $data['pay_price'] = $retArr['cast_off'];
        }
        $order = self::create($data);
        $orderInfo = self::where('id', $order->id)->field('id,order_no')->find();
        return $this->returnRight($orderInfo);
    }

    /**
     * @param $data
     * @return array
     * 更新订单
     */
    public function updateOrder($data)
    {
        $where[] = ['order_no', 'in', $data['order_no']];
        $res = self::where([$where])->update(['book_id' => $data['book_id']]);
        if ($res) {
            return $this->returnSucc();
        } else {
            return $this->returnError(1);
        }
    }

    /**
     * @param $data
     * 我的购物车
     */
    public function getMyCart($where, $field, $order, $page, $pageSize)
    {
        $data = [
            'count' => 0,
            'list' => [],
        ];

        $count = $this->where([$where])->count();
        if (empty($count)) {
            return $this->returnRight($data);
        }
        $list = $this->where([$where])->field($field)->order($order)->page($page, $pageSize)->select();
        $listArr = [];
        foreach ($list->toArray() as $item) {
            $bookInfo = Book::where('id', $item['book_id'])->field('start_time start_str,end_time end_str')->find();
            !empty($bookInfo) && $item['time_str'] = $bookInfo['start_str'] . '-' . $bookInfo['end_str'];
            !empty($bookInfo) || $item['time_str'] = '';
            $item['grade_name'] = '';
            $item['name'] = '';
            $item['avatar'] = '';
            switch ($item['order_type']) {
                //助教
                case 1:
                case 4:
                    $assis = Assistant::where('id', $item['re_id'])->field('id,nickname,grade_id,avatar')->find();
                    if (!empty($assis)) {
                        $item['grade_name'] = Grade::where('id', $assis['grade_id'])->value('grade_name') ?: '';
                        $item['name'] = $assis['nickname'];
                        $item['avatar'] = $assis['avatar'];
                    }
                    break;
                //包间
                case 2:
                    $room = Room::where('id', $item['re_id'])->field('id,room_title,room_cover')->find();
                    if (!empty($room)) {
                        $item['grade_name'] = '';
                        $item['name'] = $room['room_title'];
                        $item['avatar'] = $room['room_cover'];
                    }
                    break;
                //道具
                case 3:
                    $prop = Prop::where('id', $item['re_id'])->field('id,prop_name,prop_cover')->find();
                    if (!empty($prop)) {
                        $item['grade_name'] = '';
                        $item['name'] = $prop['prop_name'];
                        $item['avatar'] = $prop['prop_cover'];
                    }
                    break;
            }
            $listArr[] = $item;
        }
        $listRow['count'] = $count;
        $listRow['list'] = $listArr;
        return $this->returnRight($listRow);
    }

    /**
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 余额支付
     */
    public function payWithBalance($data)
    {
        //订单信息
        $orderArr = $this->where('order_no', 'in', $data['order_no'])
            ->field('id,member_id,re_id,store_id,order_count,order_type,is_cart,pay_price,pay_status')
            ->select();
        $orderList = $orderArr->toArray();
        //本人订单不可预约
        $memberIds = array_column($orderList, 'member_id');
        //原用户id数组
        $memberArr[] = $data['member_id'];
        $diffArr = array_diff($memberIds, $memberArr);
        if (!empty($diffArr)) {
            return $this->returnError(42);
        }
        $payStatus = array_column($orderList, 'pay_status');
        if (in_array(1, $payStatus)) {
            return $this->returnError(41);
        }
        //查询用户信息
        $memberInfo = Member::where('member_id', $data['member_id'])
            ->field('nickname,balance,role,identify')
            ->find();
        $sum = 0;
        foreach ($orderList as $item) {
            $sum += (int)($item['pay_price'] * 100);
        }
        $totalPrice = $sum / 100;
        //查询助教信息
        //余额不足
        if ($memberInfo['balance'] < $totalPrice) {
            return $this->returnError(40);
        } else {
            try {
                $this->startTrans();
                //更改订单状态
                $bookIds = $this->where('order_no', 'in', $data['order_no'])->column('book_id');
                $this->where('order_no', 'in', $data['order_no'])
                    ->save(['pay_status' => 1, 'pay_type' => 3]);
                //减去用户余额
                $nowBalance = $memberInfo['balance'] - $totalPrice;
                Member::update(['balance' => $nowBalance], ['member_id' => $data['member_id']]);
                //预约
                Book::where('id', 'in', $bookIds)->save(['status' => 1]);
                $this->commit();
            } catch (\Exception $ex) {
                $this->rollback();
            }
        }
        return $this->returnSucc();
    }

    /**
     * @param $data
     * @return array
     * 清空购物车
     */
    public function clearData($data)
    {
        $where[] = ['order_no', 'in', $data['order_no']];
        $res = $this->where($where)->save(['is_cart' => 0]);
        if ($res) {
            return $this->returnSucc();
        } else {
            return $this->returnError(-1);
        }
    }
}
